<?php

namespace app\home\controller;

use think\Cookie;

//公共控制器
use app\common\controller\Homecontroller;

/**
 * 收藏控制器
 */
class Comment extends Homecontroller
{
    // 构造函数
    public function __construct()
    {
        //继承底层的控制器构造函数
        parent::__construct();

        //定义一个全局模型
        $this->PostModel = model('Post.Post');
        $this->UserModel = model('User.User');
        $this->CollectModel = model('User.Collect');
        $this->CommentModel = model('Post.Comment');
        $this->RecordModel = model('User.Record');
        $this->ConfigModel  = model('Config');
    }

    // 添加评论
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->param();
            $pid = $this->request->param('pid', 0);

            $postinfo = $this->PostModel->find($params['postid']);

            if (!$postinfo) {
                $this->error('帖子不存在');
                exit;
            }

            if ($postinfo['accept']) {

                $this->error('该帖子已经采纳，无需评论');
                exit;
            }

            $comment = $this->CommentModel->find($pid);

            //根据上级pid去找评论
            if ($comment) {
                $level = $comment['level'] + 1;
            } else {
                //没有评论
                $level = 0;
            }

            $data = [
                'pid' => $pid,
                'content' => $params['content'],
                'userid' => $this->LoginUser['id'],
                'postid' => $params['postid'],
                'level' => $level
            ];

            $result = $this->CommentModel->save($data);

            if ($result === FALSE) {
                //插入失败
                $this->error($this->CommentModel->getError());
                exit;
            } else {
                //插入成功
                $this->success('评论成功', url('home/index/info', ['postid' => $params['postid']]));
                exit;
            }
        }
    }

    // 点赞
    public function thumbs()
    {
        if ($this->request->isPost()) {

            $success = [
                'result' => false,
                'msg' => ''
            ];

            // 评论的ID
            $id = $this->request->param('id', 0);

            // 单条评论的详情
            $comment = $this->CommentModel->find($id);

            if (!$comment) {
                $success['msg'] = '该评论不存在';
                exit;
            }

            $visit = trim($comment['like']);
            $VisitArr = explode(',', $visit); //转换成数组
            $VisitArr = array_filter($VisitArr); //去除数组中的空元素

            // 用户id
            $userid = $this->LoginUser['id'];

            // 判断数组里面是否有用户id
            if (in_array($userid, $VisitArr)) {
                // 已点赞
                foreach ($VisitArr as $key => $item) {
                    if ($userid == $item) {
                        // 删除数组的元素
                        unset($VisitArr[$key]);
                    }
                }
                // 组装数据
                $data = [
                    'id' => $id,
                    'like' => implode(',', $VisitArr)
                ];

                $result = $this->CommentModel->isUpdate()->save($data);

                if ($result === FALSE) {
                    //点赞失败
                    $success['result'] = false;
                    $success['msg'] = $this->CommentModel->getError();
                } else {
                    //点赞成功
                    $success['result'] = true;
                    $success['msg'] = '取消点赞成功';
                }

                //将结果返回给ajax
                return json($success);
            } else {
                // 未点赞
                $VisitArr[] = $userid;
                // 组装数据
                $data = [
                    'id' => $id,
                    'like' => implode(',', $VisitArr)
                ];

                $result = $this->CommentModel->isUpdate()->save($data);

                if ($result === FALSE) {
                    //点赞失败
                    $success['result'] = false;
                    $success['msg'] = $this->CommentModel->getError();
                } else {
                    //点赞成功
                    $success['result'] = true;
                    $success['msg'] = '点赞成功';
                }

                //将结果返回给ajax
                return json($success);
            }
        }
    }

    // 采纳
    public function accept()
    {
        if ($this->request->isPost()) {

            $success = [
                'result' => false,
                'msg' => ''
            ];

            // 评论的ID
            $comid = $this->request->param('comid', 0);

            // 单条评论的详情
            $comment = $this->CommentModel->find($comid);


            if (!$comment) {
                $success['msg'] = '该评论不存在';
                exit;
            }

            $postinfo = $this->PostModel->find($comment['postid']);

            if (!$postinfo) {

                $success['msg'] = '该帖子不存在';
                exit;
            }

            $userid = $this->LoginUser['id'];

            $userinfo = $this->UserModel->find($comment['userid']);

            if ($postinfo['userid'] != $userid) {

                $success['msg'] = '没有权限采纳';
                exit;
            }

            // if ($postinfo['accept']) {
            //     $success['msg'] = '该帖子已采纳，无需再采纳';
            //     exit;
            // }
            //开启事务
            $this->PostModel->startTrans();
            $this->CommentModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            // 帖子表的更新
            if (!$postinfo['accept']) {
                $postdata = [
                    'id' => $postinfo['id'],
                    'accept' => $comment['userid']
                ];
            } else {
                $postdata = [
                    'id' => $postinfo['id'],
                    'accept' => null
                ];
            }
            $postres = $this->PostModel->isUpdate()->save($postdata);

            if ($postres === FALSE) {
                $success['result'] = false;
                $success['msg'] = $this->PostModel->getError();
                return json($success);
            }

            // 评论表
            if (!$postinfo['accept']) {
                $commentdata = [
                    'id' => $comid,
                    'accept' => 1
                ];
            } else {
                $commentdata = [
                    'id' => $comid,
                    'accept' => 0
                ];
            }
            $commentres = $this->CommentModel->isUpdate()->save($commentdata);

            if ($commentres === FALSE) {
                $this->PostModel->rollback();
                $success['result'] = false;
                $success['msg'] = $this->PostModel->getError();
                return json($success);
            }

            // 更新用户表
            // bcadd 函数相加
            if (!$postinfo['accept']) {
                $UpdatePoint = bcadd($userinfo['point'], $postinfo['point']);
            } else {
                $UpdatePoint = $userinfo['point'] - $postinfo['point'];
            }
            if (!$postinfo['accept']) {
                $userdata = [
                    'id' => $userinfo['id'],
                    'point' => $UpdatePoint
                ];
            } else {
                $userdata = [
                    'id' => $userinfo['id'],
                    'point' => $UpdatePoint
                ];
            }
            $userres = $this->UserModel->isUpdate()->save($userdata);

            if ($userres === FALSE) {
                $this->PostModel->rollback();
                $this->CommentModel->rollback();
                $success['result'] = false;
                $success['msg'] = $this->PostModel->getError();
                return json($success);
            }

            // 消费积分记录表插入数据
            //根据附加功能类型去配置表里面查询相对的积分
            $StatePoint = $this->ConfigModel->where(['key' => "PostState{$postinfo['state']}"])->value('value');

            $StatePoint = is_numeric($StatePoint) ? abs($StatePoint) : 0;
            $content = "【" . $postinfo['title'] . "】采纳积分:<b>" . $postinfo['point'] . "积分</b> 置顶：<b>{$StatePoint}积分</b> - 发布时间：" . date("Y-m-d H:i");
            $recorddata = [
                'point' => $postinfo['point'],
                'content' => $content,
                'state' => 2,
                'userid' => $postinfo['userid']
            ];

            $recordres = $this->RecordModel->save($recorddata);

            if ($recordres === FALSE) {
                //插入消费记录失败
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->CommentModel->rollback();

                $success['result'] = false;
                $success['msg'] = $this->RecordModel->getError();
                return json($success);
            }

            //最终判断
            if ($postres === FALSE || $commentres === FALSE || $userres === FALSE || $recordres === FALSE) {
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->CommentModel->rollback();
                $this->RecordModel->rollback();
                $success['result'] = false;
                $success['msg'] = '采纳失败，请重新选择';
                return json($success);
            } else {
                //提交事务
                $this->UserModel->commit();
                $this->PostModel->commit();
                $this->CommentModel->commit();
                $this->RecordModel->commit();
                $success['result'] = true;
                $success['msg'] = '采纳成功，帖子完结';
                return json($success);
            }
        }
    }
}
